<template>
    <div class="upload-box">
        <div tabindex="0" class="el-upload el-upload--picture-card upload-item" @click="handleClick" >
            <div class="single-wrapper">
                <i v-if="!img" class="el-icon-plus avatar-uploader-icon u-icon "></i>
                <img v-else :src="img" alt="" class="el-upload-list__item-thumbnail">
            </div>       
            <input type="file" ref="input" @change="handleChange" accept=".jpg,.png" name="file" class="el-upload__input">
        </div>
    </div>    
</template>
    
<script>
import qiniu from '../../api/qiniu';

export default {
    props: {
        image: {
            type: String,
            default: ''
        },
    },
    model: {
        prop: 'image',
        event: 'change'
    },
    watch: {
        image(nv) {
            // console.log('image change to '+ nv);
            this.img = nv;
        }
    },
    data() {
        return {
            img: this.image,
        };
    },

    methods: {
        handleClick() {
            this.$refs.input.value = null;
            this.$refs.input.click();
        },
        handleChange(e) {
            const files = e.target.files;
            if(!files) return;
            this.uploadFiles(files);
        },
        uploadFiles(files) {
            const self = this;
            //获取token
            qiniu.getToken('product').then(res=>{
                // console.log(res);
                let token = res.data.token;
                let domain = res.data.domain;
                let key = res.data.key;
                var observer = {
                    next() {},
                    error(err) {
                        alert(err);
                        // console.log(err);
                    },
                    complete(res) {
                        self.img = `${domain}${res.key}`;
                        self.onSuccess();
                    }
                };
                //上传图片
                qiniu.upload(files[0], `${key}${files[0].name}`, token, observer);
            });
        },
        onSuccess() {
            // console.log(this.img);
            this.$emit('change', this.img);
        }
    },
        

};
</script>

<style lang="scss">
    .upload-box {
        // width: 550px;
        .upload-item {
            .single-wrapper {
                width: 100%;
                height: 100%;
                & > img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    display: block;
                }
                & > .u-icon {
                   position: absolute;
                   left: 0;
                   top: 0;
                   width: 146px;
                   height: 146px;
                   line-height: 146px;
                }
            }
        }
    }
</style>
